package leecode.字符串;

/**
 * @author wangxi created on 2021/3/27 19:46
 * @version v1.0
 */
public class ReverseWordsInAString {

    public static void main(String[] args) {
        ReverseWordsInAString obj = new ReverseWordsInAString();
        String reverseWords = obj.reverseWords("the sky is blue");

        System.out.println(reverseWords);

        System.out.println(((char)('A' + 32)));
    }

    public String reverseWords(String s) {
        if (s == null || s.length() <= 0) {
            return "";
        }
        // 去掉字符串首末、中间单词的空格
        String ss = trimSpace(s);
        // 翻转每个单词
        char[] nums = ss.toCharArray();
        int i = 0;
        for (int j = 0; j < nums.length; j++) {
            // 最后一个单词需要特殊处理
            if (j == nums.length - 1) {
                reverse(nums, i, j);
                break;
            }
            if (nums[j] == ' ') {
                reverse(nums, i, j - 1);
                i = j + 1;
            }
        }
        // 翻转整个句子
        reverse(nums, 0, nums.length - 1);
        StringBuilder buffer = new StringBuilder();
        for (char c : nums) {
            buffer.append(c);
        }
        return buffer.toString();
    }

    private String trimSpace(String s) {
        String result = "";
        // 去掉前面的空格
        int left = 0;
        while (left < s.length() && s.charAt(left) == ' ') {
            left++;
        }
        // 去掉后面的空格
        int right = s.length() - 1;
        while (right >= 0 && s.charAt(right) == ' ') {
            right--;
        }
        // 去掉单词间多余的空格
        while (left <= right) {
            char c = s.charAt(left);
            if (c != ' ') {
                result = result + c;
            } else if (result.charAt(result.length() - 1) != ' ') {
                result = result + c;
            }
            left++;
        }
        return result;
    }

    private void reverse(char[] nums, int i, int j) {
        if (nums == null || nums.length <= 0) {
            return;
        }
        while (i < j) {
            char c = nums[i];
            nums[i] = nums[j];
            nums[j] = c;
            i++;
            j--;
        }
    }
}
